package cn.fastpay.core.util;

import cn.fastpay.core.exception.BaseException;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * @author freewolf
 */
public class ErrorUtil {

    public static Map<String, Object> getErrorAttributes(Map<String, Object> errorAttributes, DefaultErrorAttributes defaultErrorAttributes, RequestAttributes requestAttributes, boolean includeStackTrace){

        // 获取error
        Throwable error = defaultErrorAttributes.getError(requestAttributes);
        Integer code = (Integer) errorAttributes.get("status");
        String message = errorAttributes.get("message").toString();
        // 判断是否是BaseException类异常
        if (error.getCause() instanceof BaseException) {
            BaseException exception = (BaseException)error.getCause();
            code = exception.getCode();
            message = exception.getMessage();
        }
        Map<String, Object> errorResponse = new HashMap<>(3);
        errorResponse.put("code", code);
        errorResponse.put("message", message);
        errorResponse.put("data", "");
        requestAttributes.setAttribute("javax.servlet.error.status_code", HttpStatus.OK.value(), 0);
        return errorResponse;
    }
}
